package com.atguigu.tingshu.common.minio.config;


import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.minio.service.FileUploadService;
import com.atguigu.tingshu.common.minio.service.impl.FileUploadServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(MinioProperties.class)
@ConditionalOnProperty(prefix = "minio", value = "enable" , havingValue = "true")
public class MinioAutoConfiguration {

    Logger logger = LoggerFactory.getLogger(this.getClass());
    @Bean
    public MinioClient minioClient(MinioProperties minioProperties) {

        try {
            //1.创建minio客户端
            MinioClient minioClient =  MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();
            //2.判断桶是否存在
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                //3.创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                logger.error("桶已存在");
            }
            return minioClient;
        } catch (Exception e){
            logger.error("minioClient创建失败：{}",e.getMessage());
            throw new GuiguException(201,"minioClient创建失败");
//            e.printStackTrace();
        }
    }

    @Bean
    public FileUploadService fileUploadService(){
        return new FileUploadServiceImpl();
    }
}
